var $modal = $('#your-modal');
var app = new Vue({
    el: "#content",
    data: {
        itemId: "",
        item: {
            itemId: "",
            itemName: "", //商品名
            createTime: "", //发布时间
            category: "", //商品分类
            payTypes: [], //支付方式
            transportTypes: [], //配送方式
            postage: "", //邮费
            sellingPrice: "", //售价
            buyPrice: "", //购买价格
            itemNew: "", //商品成色
            seoWord: "", //seo关键字
        },
        details: {
            id: "",
            details: "", //商品介绍
            reason: "", //出售简介
            imgs: ["/assets/img/a5.png", "/assets/img/a5.png"], //图片列表
            mainImg: "", //商品主图
            stock: "", //售卖库存
            sepc: [], //商品规格
        },
        categorys: [],
        disabled: true,
        disabled_2: true,
        isDisplay: "none",
        isReadonly: false,
        edit: false,
        edit_2: false
    },
    methods: {
        saveItemBase() {
            _this = this;
            var item = {};
            Object.keys(_this.item).forEach(function (key) {
                item[key] = _this.item[key];
            })
            item.createTime = null;
            // Object.keys(item).forEach(function (key) {
            //     // if(key=="postage"){

            //     // }else if (item[key] == null || item[key] == "") {
            //     //     layer.msg("请填写完整信息");
            //     //     return;
            //     // }
            // })
            var payType = "";
            for (index in item.payTypes) {
                payType += item.payTypes[index] + "";
            }
            item.payType = payType;
            var transportType = "";
            for (index in item.transportTypes) {
                transportType += item.transportTypes[index] + "";
            }
            item.transportType = transportType;
            axios({
                    url: "/item/updateBase",
                    method: "put",
                    data: item,
                    baseURL: 'http://localhost:8771'
                })
                .then(function (response) {
                    result = response.data;
                    data = result.data;
                    if (result.code == 200) {
                        layer.msg("保存成功");
                        _this.edit = false;
                        return;
                    }
                    layer.msg("报错失败");
                })
        },
        saveItemDetails() {
            _this = this;
            var item = {};
            item.reason = this.details.reason;
            item.stock = this.details.stock;
            imgs = "";
            for (index in this.details.imgs) {
                if (index == 0) {
                    imgs += this.details.imgs[index];
                    item.mainImg = this.details.imgs[index];
                } else {
                    imgs += "^" + this.details.imgs[index];
                }
            }
            item.specification = JSON.stringify(this.details.sepc);
            item.imgs = imgs;
            item.details = editor.txt.html();
            item.id = this.details.id;
            itemAxios.put("/details", item)
                .then(function (response) {
                    result = response.data;
                    if (result.code == 200) {
                        layer.msg("更新数据成功");
                        _this.edit_2 = false;
                        return;
                    }
                })
        },
        initCategory() {
            _this = this;
            itemAxios.get("/category/categoryList")
                .then(function (response) {
                    result = response.data;
                    _this.categorys = result.data;
                })
        },
        addGuige() {
            if (this.details.sepc.length >= 20) {
                $modal.modal();
                return;
            }
            this.details.sepc.push({
                name: "",
                value: ""
            });
            var list = this.details.sepc;
            console.log(list.length)
        },
        deleteGuige(index) {
            this.details.sepc.splice(index, 1);
        },
        loadItem() {
            THIS = this;
            var itemId = getUrlParam("itemid");
            itemAxios.get("/item", {
                params: {
                    itemId: itemId
                }
            }).then(function (response) {
                result = response.data;
                if (result.code == 200) {
                    data = result.data;
                    var item = {};
                    item.itemId = data.itemId;
                    item.itemName = data.itemName;
                    item.createTime = dateFormat(data.createTime);
                    item.category = data.category;
                    data.payType += "";
                    var payTypes = new Array();
                    for (index in data.payType) {
                        payTypes.push(data.payType[index]);
                    }
                    item.payTypes = payTypes;
                    var transportTypes = new Array();
                    data.transportType += "";
                    for (index in data.transportType) {
                        transportTypes.push(data.transportType[index]);
                    }
                    item.transportTypes = transportTypes;
                    item.postage = data.postage;
                    item.sellingPrice = data.sellingPrice;
                    item.buyPrice = data.buyPrice;
                    item.itemNew = data.itemNew;
                    item.seoWord = data.seoWord;

                    var details = {};
                    details.id = data.detailId;
                    details.details = data.details;
                    details.reason = data.reason;
                    details.imgs = data.imgs.split("^");
                    details.stock = data.stock;
                    details.sepc = JSON.parse(data.specification);
                    THIS.item = item;
                    THIS.details = details;
                    THIS.$nextTick(function () {
                        editor.create();
                        editor.$textElem.attr('contenteditable', false)
                    })
                }
            })
        },
        editBase() {
            this.edit = !this.edit ;
        },
        editDetails() {
            this.edit_2 = !this.edit_2;
            editor.$textElem.attr('contenteditable', this.edit_2);
        }
    }
});
app.initCategory();
app.loadItem();
layui.use(['layer', 'form'], function () {});
//初始化编辑器 begin
var E = window.wangEditor
var editor = new E('.editor')
// 或者 var editor = new E( document.getElementById('editor') )
editor.customConfig.uploadImgServer = 'http://localhost:8000/res/uploadImg';
editor.customConfig.uploadFileName = 'imgFile'
editor.customConfig.uploadImgHooks = {
    before: function (xhr, editor, files) {
        // 图片上传之前触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件
        // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
        // return {
        //     prevent: true,
        //     msg: '放弃上传'
        // }
    },
    success: function (xhr, editor, result) {
        // 图片上传并返回结果，图片插入成功之后触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
    },
    fail: function (xhr, editor, result) {
        // 图片上传并返回结果，但图片插入错误时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
    },
    error: function (xhr, editor) {
        // 图片上传出错时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
    },
    timeout: function (xhr, editor) {
        // 图片上传超时时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
    },
    // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
    // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
    customInsert: function (insertImg, result, editor) {
        // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
        // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
        // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
        var url = result.data[0];
        insertImg(url)
        // result 必须是一个 JSON 格式字符串！！！否则报错
    }
}

//初始化编辑器 end
function upImg(file) {
    // var file = $('#upCover').get(0).files[0];
    var form = new FormData();
    form.append("imgFile", file)
    // alert(app._name);
    $.ajax({
        url: "http://localhost:8000/res/uploadImg",
        type: "post",
        data: form,
        dataType: "JSON",
        cache: false,
        processData: false,
        contentType: false,
        success: function (data) {
            app.details.imgs.push(data.data[0]);
            // $("#userImg").attr("src", data.data[0]);

        },
        error: function () {
            alert("error")
        }
    })
}